﻿using JumpKick.HttpLib;
using Newtonsoft.Json;
using SharpEncrypt4.Lib;
using SharpEncrypt4l_Lib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Runtime.Caching;
using YiHaoHospitalPlatform.Model;

namespace YiHaoHospitalPlatform
{
    public sealed class CommitPatientInstance
    {
        #region 局部变量
        /// <summary>
        /// 病人数据缓存
        /// </summary>
        private static MemoryCache PatientCache = MemoryCache.Default;
        /// <summary>
        /// 要提交的病人列表
        /// </summary>
        private static List<Patient> patientList = new List<Patient>();
        /// <summary>
        /// 要提交的检查列表
        /// </summary>
        private static List<Inspect> inspectList = new List<Inspect>();
        /// <summary>
        /// 公钥
        /// </summary>
        private static string publicKey;
        /// <summary>
        /// 平台接口地址
        /// </summary>
        private static string platformUrl;
        /// <summary>
        /// 平台分配的机构代码
        /// </summary>
        private static string orgId;
        /// <summary>
        /// 缓存时间
        /// </summary>
        private static int cacheMinutes = 600;
        /// <summary>
        /// 检索病人信息action
        /// </summary>
        private static Action QueryPatientAction;
        /// <summary>
        /// 成功action
        /// </summary>
        private static Action<string> LoopCommitAction = new Action<string>(commitPatient);
        /// <summary>
        /// 失败action
        /// </summary>
        private static Action<WebException> FailLoopCommitAction = new Action<WebException>(RetryCommitPatient);
        #endregion
        #region 单利模式
        private static readonly Lazy<CommitPatientInstance> instance = new Lazy<CommitPatientInstance>(() =>
        {
            if (publicKey == null)
            {
                publicKey = ConfigurationManager.AppSettings["publicKey"];
            }
            if (platformUrl == null)
                platformUrl = ConfigurationManager.AppSettings["platform_url"];
            if (orgId == null)
                orgId = ConfigurationManager.AppSettings["org_id"];
            cacheMinutes = int.Parse(ConfigurationManager.AppSettings["patient_cache_minutes"]);
            return new CommitPatientInstance();
        });
        private CommitPatientInstance() { }
        public static CommitPatientInstance Instance
        {
            get
            {
                return instance.Value;
            }
        }
        #endregion
        /// <summary>
        /// 设置本地检索数据的action
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public CommitPatientInstance setQueryPatientAction(Action action)
        {
            QueryPatientAction = action;
            return Instance;
        }
        /// <summary>
        /// 向服务器提交数据，只需调用一次，内部会循环调用获取数据的方法
        /// </summary>
        /// <param name="patients">病人列表</param>
        /// <returns></returns>
        public bool StartCommitPatients(List<Patient> patients)
        {
            if (QueryPatientAction == null)
                throw new Exception("请先设置QueryPatientAction");
            if (patients != null)
                //组织要提交的数据
                foreach (Patient patient in patients)
                {
                    //判断缓存中是否有该数据
                    Patient cache = PatientCache[patient.ZYH] as Patient;
                    if (cache == null)
                    {
                        patient.isNew = true;
                        patientList.Add(patient);
                        AddCache(patient);
                    }
                    else if (!cache.Equals(patient))
                    {
                        patient.isNew = false;
                        patientList.Add(patient);
                        AddCache(patient);
                    }
                }
            commitPatient(null);
            return true;
        }

        private static void RetryCommitPatient(WebException ex)
        {
            commitPatient(null);
        }
        /// <summary>
        /// 递归调用，向服务器逐条提交数据
        /// </summary>
        private static void commitPatient(string commitSuccess)
        {
            if (patientList.Count > 0 && commitSuccess != null)
                patientList.RemoveAt(0);
            if (patientList.Count > 0)
            {
                string json = JsonConvert.SerializeObject(patientList[0]);
                Console.WriteLine(json);
                string encryptPatient = EncryptProvider.RSAEncrypt(RSAKeyConvert.RSAPublicKeyJava2DotNet(publicKey), json);
                Http.Post(platformUrl).Form(new { orgId = orgId, data = encryptPatient })
                    .OnSuccess(LoopCommitAction)
                    .OnFail(FailLoopCommitAction)
                    .Go();
            }
            else
            {
                QueryPatientAction.BeginInvoke(null, null);
            }
        }
        /// <summary>
        /// 向缓存中添加数据
        /// </summary>
        /// <param name="department"></param>
        private void AddCache(Patient patient)
        {
            Patient cache = PatientCache[patient.ZYH] as Patient;
            if (cache != null)
                PatientCache.Remove(patient.ZYH);
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes);//取得或设定值，这个值会指定是否应该在指定期间过后清除
            PatientCache.Set(patient.ZYH, patient, policy);
        }
    }
}
